package com.qf.service.impl;

import com.qf.constant.CacheConstants;
import com.qf.constant.OperatorConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainService;
import com.qf.util.CheckMobileOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Set;

/**
 * @author Zwnan
 */
@Service("phase")
public class PhaseFilterServiceImpl implements FilterChainService {

    @Autowired
    private CacheFeign cacheFeign;

    @Override
    public boolean stratrgy(StandardSubmit submit) {
        //根据手机号查询所在省市
        String destMobile = submit.getDestMobile();
        String mobile = destMobile.substring(0, 7);
        String key = CacheConstants.CACHE_PREFIX_PHASE+mobile;
        String value = cacheFeign.get(key);
        if (StringUtils.isEmpty(value)){
            submit.setProvinceId(0);
            submit.setCityId(0);
        }else {
            String[] m = value.split(",");
            submit.setProvinceId(Integer.parseInt(m[0]));
            submit.setCityId(Integer.parseInt(m[1]));
        }

        //根据手机号判断移动联通电信
        if (CheckMobileOperator.isChinaMobilePhoneNum(destMobile)){
            submit.setOperatorId(OperatorConstants.CHINA_MOBILE);
        }else if (CheckMobileOperator.isChinaUnicomPhoneNum(destMobile)){
            submit.setOperatorId(OperatorConstants.CHINA_UNICOM);
        }else if (CheckMobileOperator.isChinaTelecomPhoneNum(destMobile)){
            submit.setOperatorId(OperatorConstants.CHINA_TELECOM);
        }else {
            submit.setOperatorId(OperatorConstants.CHINA_UNKNOWN);
        }

        //CHANNEL:0:4

        String channelKey = CacheConstants.CACHE_PREFIX_SMS_CHANNEL+"*";

        Set<String> channelSets =  cacheFeign.keys(channelKey);

        for (String channelSet : channelSets) {
            if (channelKey.startsWith(CacheConstants.CACHE_PREFIX_SMS_CHANNEL+submit.getOperatorId())){
                String[] split = channelSet.split(":");
                submit.setGatewayID(Integer.parseInt(split[2]));
            }
        }

        //号段补全策略实现   需要使用spNumber（channel表） + extendNumber（client_channel表）
        String s = CacheConstants.CACHE_PREFIX_SMS_CHANNEL + submit.getOperatorId() + ":" + submit.getGatewayID();
        String spNumber = cacheFeign.hget(s,"spnumber");

        String l = CacheConstants.CACHE_PREFIX_ROUTER + submit.getClientID() + ":" + submit.getOperatorId();
        String extendNumber = cacheFeign.hget(s,"extendnumber");
        submit.setSrcNumber(spNumber+extendNumber);


        return true;
    }
}
